const tool = require('../tools/tool')
// const permissions = require('../methods/permissions')
// const user = require('../methods/user')
// const patrol = require('./patrol')
const db = require('../db')

const task = {
    list: [],
    running: false,
    async run() {
        if (this.running) return
        this.running = true
        while (1) {
            await tool.wait(5)
            let current = this.list[0]
            if (!current) continue
            tool.sendMessage(current.phone, current.content)
            this.shift()
        }
    },
    add(phone, content) {
        const handle = () => this.list.push({ phone, content })
        handle()
    },
    shift() {
        this.list.shift()
    }
}

task.run()

module.exports = {
    toPhone(phone, content) {
        task.add(phone, content)
    },
    toUser: {
        async byOpenId(openId, content) {
            let userData = await tool.methods.user().getSingleUserInfoByOpenId(openId, true)
            if (!userData) throw '用户不存在'
            task.add(userData.phone, content)
        },
        async byUserId(userId, content) {
            let userData = await tool.methods.user().getSingleUserInfoByUserId(userId, true)
            if (!userData) throw '用户不存在'
            task.add(userData.phone, content)
        },
        async byAccount(account, content) {
            let userData = await tool.methods.user().getSingleUserInfoByAccount(account, true)
            if (!userData) throw '用户不存在'
            task.add(userData.phone, content)
        },
    },
    async toDepartment(departmentId, content, role) {
        let users = await db.selectWithParams(`select * from users where departmentId = ? ${role === undefined ? `` : `and role = ?`}`, [departmentId, (() => {
            if (role === undefined) return []
            return [role]
        })()])
        for (let i = 0; i < users.length; i++) {
            task.add(users[i].phone, content)
        }
    },
    async toHandleGroup(campusId, categoryId, content) {
        let users = await db.selectWithParams(`select * from permissions where campusId = ? and categoryId = ? and type = 1`, [campusId, categoryId])
        for (let i = 0; i < users.length; i++) {
            let userData = await tool.methods.user().getSingleUserInfoByUserId(users[i].userId)
            if (userData) task.add(userData.phone, content)
        }
    },
    async toReviewGroup(campusId, categoryId, content) {
        let users = await db.selectWithParams(`select * from permissions where campusId = ? and categoryId = ? and type = 2`, [campusId, categoryId])
        for (let i = 0; i < users.length; i++) {
            let userData = await tool.methods.user().getSingleUserInfoByUserId(users[i].userId)
            if (userData) task.add(userData.phone, content)
        }
    },
    async toRole(role, content) {
        let users = await db.selectWithParams(`select * from users where role = ?`, [role])
        for (let i = 0; i < users.length; i++) {
            task.add(users[i].phone, content)
        }
    },
    async toPatrolCreater(patrolId, content) {
        const patrol = require('./patrol')
        let patrolInfo = await tool.methods.patrol().getHead(patrolId)
        if (!patrolInfo) throw '巡查不存在'
        const user = require('./user')
        let userData = await tool.methods.user().getSingleUserInfoByUserId(patrolInfo.userId)
        if (!userData) throw '用户不存在'
        task.add(userData.phone, content)
    },
    async toAdmin(content) {
        let users = await db.selectWithParams(`select * from users where isAdmin = 1`)
        for (let i = 0; i < users.length; i++) {
            task.add(users[i].phone, content)
        }
    },
    async getPatrolInMessageFormat(patrolId, callBack = (infoStr, singleItem) => { }) {
        const patrol = require('./patrol')
        let patrolInfo = await tool.methods.patrol().format(await tool.methods.patrol().get.single(patrolId, undefined, true))
        if (!patrolInfo) throw '巡查不存在'
        try {
            return callBack(`【#${patrolInfo.id}】巡查内容：
• 巡查人：${patrolInfo.userData.username} 手机号：${patrolInfo.userData.phone}
• 状态：${patrolInfo.status_read}
• ${patrolInfo.campusInfo.name}-${patrolInfo.categoryInfo.name}
• 描述：${patrolInfo.desc}
• ${patrolInfo.imageList.length ? `图片${patrolInfo.imageList.length}张` : ``} ${patrolInfo.showMap ? '定位(小程序内查看)' : ''} 处理${patrolInfo.detail.num.handle}次 驳回${patrolInfo.detail.num.review}次 评价${patrolInfo.detail.num.feedback}次
• 巡查于 ${patrolInfo.createdAt_read}
• 截止于 ${patrolInfo.endTime_read}`, patrolInfo)
        } catch (error) {

        }
    }
}